#!/usr/bin/env python
#coding=utf-8

import MultipartPostHandler
import urllib2
import cookielib
import os
import json
import config
import httplib2
from urllib import urlencode

BDUSS = config.BAIDU_BDUSS
Cookie = config.BAIDU_COOKIE
bdstoken = config.BAIDU_bdstoken

h = httplib2.Http()

header = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'),
          ('Accept', 'application/json, text/javascript, */*; q=0.01'),
          ('Connection', 'keep-alive'),
          ('Cookie', Cookie),
          ('X-Requested-With','XMLHttpRequest')]
                  
class BaiduDL(object):

    def __init__(self):
        self.cookies = cookielib.CookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
        self.opener.addheaders = header
        
    def get_torrent_id(self, baidu_source_url):
        #通过百度离线的source_url得到oid
        get_url = config.MY_DATAQUERY_URL + '&type=get_torrent_id&baidu_source_url=' + baidu_source_url
        head, ret = h.request(get_url)
        print ret
        return int(ret)

    def get_task_info(self):
        #获取百度任务列表
        get_url = 'http://pan.baidu.com/rest/2.0/services/cloud_dl?bdstoken=' + bdstoken + '&method=list_task&app_id=250528&need_task_info=1&status=255&t=1380884593062'
        ret = json.loads(self.opener.open(get_url).read())
        print ret;
        #status0 success5 faild1 unkown 7 deleted
        
    def upload_torrent_and_add_task(self, path, torrent_oid) :
        torrent_name = torrent_oid + '.torrent'
        post_url = 'http://c.pcs.baidu.com/rest/2.0/pcs/file?method=upload&type=tmpfile&app_id=250528&BDUSS=' + BDUSS
        cookies = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies), MultipartPostHandler.MultipartPostHandler)
        params = { "Filename" : torrent_name, "Filedata" : open(path + torrent_name, "rb"), "Upload" : "Submit Query"}
        opener.addheaders = [('User-Agent', 'Shockwave Flash'),  
                       ('Accept', 'text/*'),  
                       ('Connection', 'keep-alive'),  
                       ('Cookie', Cookie)]
        ret = json.loads(opener.open(post_url, params).read())
        if not ret.has_key('md5'):
            print '种子文件上传失败'
            return 1

        #上传完毕之后需要调用创建接口才能真正完成种子上传
        post_url = 'http://pan.baidu.com/api/create?a=commit&channel=chunlei&clienttype=0&web=1'
        post_data = 'path=%2F' + torrent_name + '&isdir=0&size=' + str(os.path.getsize(path + torrent_name)) + '&block_list=%5B%22' + ret['md5'] + '%22%5D&method=post'
        ret = json.loads(self.opener.open(post_url, post_data).read())
        if not ret.has_key('errno'):
            print '种子文件创建失败'
            return 2
        if not ret['errno'] == 0:
            print '种子文件创建失败,服务器返回错误代码:' + str(et['errno'])
            return 3
        
        #服务器上最后保存的文件名,有可能因为重名被重命名ret['server_filename'] 完整路径ret['path']
        #获取种子详细信息
        get_url = 'http://pan.baidu.com/rest/2.0/services/cloud_dl?bdstoken=' + bdstoken + '&app_id=250528&method=query_sinfo&source_path=' + ret['path'] + '&type=2&t=1380788693710'
        ret2 = json.loads(self.opener.open(get_url).read())
        print ret2
        if not ret2.has_key('torrent_info'):
            print '百度解析种子文件失败'
            return 4
        if ret2['total'] == None or ret2['total'] == 0:
            print '百度认为上传的种子内容为空?'
            return 5

        #添加离线任务
        post_url = 'http://pan.baidu.com/rest/2.0/services/cloud_dl?bdstoken=' + bdstoken
        idx_lst = '1'
        for i in range(2, ret2['total'] + 1):
            idx_lst += '%2C' + str(i)
        post_data = 'method=add_task&app_id=250528&source_path=' + ret['path'] + '&file_sha1=' + ret2['torrent_info']['sha1'] + '&save_path=%2F' + config.BAIDU_SAVE_DIR + '&type=2&selected_idx=' + idx_lst + '&task_from=2&t=1380805095518'
        if not 200 == self.opener.open(post_url, post_data).code :
            return 1
        
        #完成添加操作,将ret['path']更新入数据库
        m = {'baidu_source_url' : ret['path']}
        s = urlencode(m)
        get_url = config.MY_DATAQUERY_URL + '&type=update_source_url&ori_torrent_id=' + torrent_oid + '&' + s
        print get_url
        h.request(get_url)
        return 0

if __name__ == "__main__":
    baidudl = BaiduDL()
    baidudl.get_task_info()
    baidudl.upload_torrent_and_add_task('D:\code\python\NexusGet\\', '123')
    baidudl.get_torrent_id('/123(3).torrent')
